package org.cmind.soap.android;

import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

import org.xmlpull.v1.XmlSerializer;

import android.util.Xml;

public class SoapToXml {

    NamespaceHelper nsh;

    private void produceXml(XmlSerializer serializer, SoapObject so) throws IllegalArgumentException,
            IllegalStateException, IOException {

        String namespace = so.getNamespace();
        String tagName = so.getName();
        if (namespace != null && !"".equals(namespace) && nsh.getPrefixForNs(namespace) == null) {
            String prefix = nsh.registerNewNameSpace(namespace);
            serializer.setPrefix(prefix, so.getNamespace());
            // tagName = prefix + ":" + tagName;
        } else if (nsh.getPrefixForNs(namespace) != null) {
            tagName = nsh.getPrefixForNs(namespace) + ":" + tagName;
            namespace = null;
        }
        serializer.startTag(namespace, tagName);
      if (so.getAttributes() != null) {
            List<Attribute> attibutes = so.getAttributes();
            for (Attribute attr : attibutes) {
                //TODO poprawic
                serializer.attribute(attr.getNameSpace(), attr.getName(), attr.getValue());
            }
        }
        if (so.getChilds() != null) {
            for (SoapObject s : so.getChilds()) {
                produceXml(serializer, s);
            }
        } else {
            serializer.text(so.getValue());
        }
        serializer.endTag(namespace, tagName);

    }

    public String produceXml(SoapObject root) {
        XmlSerializer serializer = Xml.newSerializer();
        nsh = new NamespaceHelper();
        StringWriter writer = new StringWriter();
        try {
            serializer.setOutput(writer);
            serializer.startDocument("UTF-8", true);
            produceXml(serializer, root);
            serializer.endDocument();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return writer.toString();
    }

}
